#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>

#pragma pack(1)
typedef struct {
    union {
		uint16_t type;
		uint8_t type_b[2];
	};
    uint32_t size;
    uint16_t rsvd1;
    uint16_t rsvd2;
    uint32_t offbits;
} bmp_file_header;
#pragma pack()

typedef struct {
	uint32_t size;
	int32_t width;
	int32_t height;
	uint16_t planes;
	uint16_t bpp;
	uint32_t compression;
	uint32_t size_image;
	int32_t xppm; //x pels per meter
	int32_t yppm;
	uint32_t color_used;
	uint32_t color_important;
} __attribute((aligned (1))) bmp_info_header;

FILE *fbmp=NULL;
bmp_file_header bmp_h;
bmp_info_header bmp_i;
int32_t rgba[256]; //palatte

void bmp_file_header_read(bmp_file_header* fh,bmp_info_header* ih);

int main(int argc, char** argv) {
	if(2<=argc && NULL!=argv[1] && 0!=strcmp(argv[1],"")) {
		fbmp=fopen(argv[1],"rb");
		if(NULL==fbmp) {
			printf("%s open failed\n",argv[1]);
			return 0;
		}
	} else {
		printf("no file arg\n");
		return 0;
	}
	
	memset(&bmp_h,0,sizeof(bmp_file_header));
	memset(&bmp_i,0,sizeof(bmp_info_header));
	fread(&bmp_h,sizeof(bmp_file_header),1,fbmp);
	fread(&bmp_i,sizeof(bmp_info_header),1,fbmp);
	bmp_file_header_read(&bmp_h,&bmp_i);
	
	uint8_t rest=0;
	int rest_cnt=0;
	while(1) {
		if(1==fread(&rest,sizeof(uint8_t),1,fbmp)) {
			++rest_cnt;
		} else {
			break;
		}
	}
	printf("rest_cnt=%d\n",rest_cnt);

	fclose(fbmp);
}

void bmp_file_header_read(bmp_file_header* fh,bmp_info_header* ih) {
	printf("\n=====================\n");
	//printf("type   =%c%c\n",fh->type_b[0],fh->type_b[1]);
	printf("type   =0x%-8x\n",fh->type);
	printf("size   =0x%-8x\n",fh->size);
	printf("rsvd1  =0x%-8x\n",fh->rsvd1);
	printf("rsvd2  =0x%-8x\n",fh->rsvd2);
	printf("offbits=0x%-8x\n",fh->offbits);

	printf("\n======================\n");
	printf("size       =0x%4x\n",ih->size);
	printf("width      =0x%4x\n",ih->width);
	printf("height     =0x%4x\n",ih->height);
	printf("planes     =0x%4x\n",ih->planes);
	printf("bpp        =0x%4x\n",ih->bpp);
	printf("compression=0x%4x\n",ih->compression);
	printf("size_image =0x%4x\n",ih->size_image);
	printf("xppm       =0x%4x\n",ih->xppm);
	printf("yppm       =0x%4x\n",ih->yppm);
	printf("color_used =0x%4x\n",ih->color_used);
	printf("color_imprt=0x%4x\n",ih->color_important);
}
